// TCP Server端设计
package main

import (
    "net"
    "fmt"
    "os"
)

func main() {
    service := ":5000"
    tcpAddr, err := net.ResolveTCPAddr("tcp",service)
    CheckError(err)
    listener, err := net.ListenTCP("tcp", tcpAddr)
    CheckError(err)
    for {
        conn, err := listener.Accept()
        if err != nil {
            continue
        }
        handleClient(conn)
        conn.Close()
    }
}

func handleClient(conn net.Conn) {
    var buf [512]byte
    for {
        n,err:= conn.Read(buf[0:])
        if err != nil {
            return
        }
        rAddr := conn.RemoteAddr()
        fmt.Println("Receive from client", rAddr.String(), string(buf[0:n]))
        _, err2 := conn.Write([]byte("Welcome client!"))
        if err2 != nil {
            return
        }
    }
}

func CheckError(err error)  {
    if err != nil {
        fmt.Fprintf(os.Stderr, "Fatal error: %s", err.Error())
        os.Exit(1)
    }
}
